package com.zfy.cmsservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zfy.cmsservice.entity.Subjects;
import com.zfy.cmsservice.entity.excel.SubjectData;
import com.zfy.cmsservice.service.SubjectsService;


import java.awt.print.PrinterException;

public class SubjectExcelLister extends AnalysisEventListener<SubjectData> {
    public SubjectsService subjectService;

    public SubjectExcelLister(SubjectsService subjectService) {
        this.subjectService = subjectService;
    }
    public SubjectExcelLister() {}
    //读取execl内容   一行一行取
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData == null){
            try {
                throw new PrinterException("文件数据为空");
            } catch (PrinterException e) {
                throw new RuntimeException(e);
            }
        }
        //添加一级分类是否重复
        Subjects existOneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
        if(existOneSubject == null){ //没有一级分类继续添加
            existOneSubject = new Subjects();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(existOneSubject);
        }
        //取得一级分类id值
        String pid = existOneSubject.getId();
        //二级分类是否重复
        Subjects existTwoSubject = this.existTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);
        if(existTwoSubject == null){ //没有一级分类继续添加
            existTwoSubject = new Subjects();
            existTwoSubject.setParentId(pid);
            existTwoSubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(existTwoSubject);
        }
    }
    //判断一级分类是否重复
    private Subjects existOneSubject(SubjectsService subjectService, String
            name) {
        QueryWrapper<Subjects> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        Subjects oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }
    //判断二级分类是否重复
    private Subjects existTwoSubject(SubjectsService subjectService,String
            name,String pid) {
        QueryWrapper<Subjects> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        Subjects twoSubject = subjectService.getOne(wrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
